package com.hunantv.mglive.ui.discovery.publisher.pic;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.MediaStore.Images.ImageColumns;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Images.Thumbnails;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;

import com.hunantv.mglive.common.MaxApplication;

/**
 * @author maxxiang
 * 
 *         Create On: 2014-7-16
 */
public class PicQueryMgr implements IPicQuery {
	private static final String TAG = PicQueryMgr.class.getSimpleName();
	private static PicQueryMgr mQuery;

	protected Context mContext;
	private ContentResolver mResolver;

	private Uri URI_MEDIA = Media.EXTERNAL_CONTENT_URI; // 原图
	private Uri URI_THUMBNAILS = Thumbnails.EXTERNAL_CONTENT_URI; // 缩略图

	public static PicQueryMgr getInstance() {
		if (mQuery == null) {
			mQuery = new PicQueryMgr();
			mQuery.init();
		}
		return mQuery;
	}

	public void init() {
		mContext = MaxApplication.getAppContext().getApplicationContext();
		mResolver = mContext.getContentResolver();
	}

	@Override
	public void queryPicList(String albumId, IPicQueryFinished callback) {
		ImgWorkThread.getInstance().postToWorkThread(
				new QueryPicListOfAlbumRunnable(albumId, callback));
	}

	// 查询相册的异步类， albumName为空则查最近相册。
	private class QueryPicListOfAlbumRunnable implements Runnable {
		IPicQueryFinished mCallback;
		String mAlbumId;

		public QueryPicListOfAlbumRunnable(String albumId,
				IPicQueryFinished callback) {
			mAlbumId = albumId;
			mCallback = callback;
		}

		@Override
		public void run() {
			ArrayList<PicItem> picItems = queryPicListOfAlbum(mAlbumId);
			
			mCallback.onQueryPicFinished(picItems);
		}

	}

	private String[] getColumns() {
		return new String[] { ImageColumns._ID, Media.DATA,
				ImageColumns.DATE_MODIFIED, ImageColumns.ORIENTATION,
				ImageColumns.SIZE };

		// new String[]{BaseColumns._ID,MediaColumns.DATA,
		// MediaColumns.DATE_ADDED}
	}

	// ****************************************************************************************
	// 功能：对外的接口，查询相册里的图片list
	// ****************************************************************************************
	public ArrayList<PicItem> queryPicListOfAlbum(String albumId) {
		if (albumId == null
				|| PicQueryConstants.RECENT_ALBUM_ID.equals(albumId)) { // 最近照片
			return queryRecentPics(PicQueryConstants.RECENT_PHOTO_MIN_WIDTH,
					PicQueryConstants.MAX_RECENT_PHOTO_NUM, false);
		} else {
			return queryAlbumPics(albumId,
					PicQueryConstants.RECENT_PHOTO_MIN_WIDTH, PicQueryConstants.MAX_SINGLE_PHOTO_NUM, false);
		}
	}

	// 功能：查询最近相册的数据
	private ArrayList<PicItem> queryRecentPics(int limitWidth, int limit,
			boolean isContainGif) {
		ArrayList<PicItem> picItems = new ArrayList<PicItem>();

		// 准备selector 查询的参数. todo:后面要加上判断尺寸的条件
		String selector = ImageColumns.SIZE + ">10000 " + ") GROUP BY ("
				+ Media.DATA;
		int realLimit = limit;
		Uri uri = null;
		Uri.Builder builder = Media.EXTERNAL_CONTENT_URI.buildUpon();
		builder.appendQueryParameter("limit", String.valueOf(realLimit));
		uri = builder.build();

		Cursor cursor = mResolver.query(URI_MEDIA, getColumns(), selector,
				null, getOrderBy());

		if (cursor == null) {
			return picItems;
		}
		try {
			getImageList(cursor, picItems, limitWidth, limit, isContainGif);
		} catch (Exception e) {
			Log.d(TAG, e.getMessage());
		} finally {
			if (cursor != null)
				cursor.close();
		}

		return picItems;
	}

	// 功能：查询某个相册的图片
	private ArrayList<PicItem> queryAlbumPics(String albumId, int limitWidth,
			int limit, boolean isContainGif) {
		ArrayList<PicItem> picItems = new ArrayList<PicItem>();

		// 准备selector 查询的参数
		String selector = Media.BUCKET_ID + "='" + albumId + "'";

		Cursor cursor = mResolver.query(URI_MEDIA, getColumns(), selector,
				null, getOrderBy());

		if (cursor == null) {
			return picItems;
		}

		try {
			getImageList(cursor, picItems, limitWidth, limit, isContainGif);
		} catch (Exception e) {
			Log.d(TAG, e.getMessage());
		} finally {
			if (cursor != null)
				cursor.close();
		}

		return picItems;
	}

	// 功能： 从已经查询到的cursor中取出所有图片
	private static void getImageList(Cursor cursor,
			ArrayList<PicItem> picItems, int limitWidth, int maxCount, boolean isContainGif) {

		int count = cursor.getCount();
		if (count > 0) {

			int n=0;
			if (cursor.moveToFirst()) {
				do {
					String path = cursor.getString(cursor
							.getColumnIndexOrThrow(Media.DATA));
					Long id = cursor.getLong(cursor
							.getColumnIndexOrThrow(ImageColumns.ORIENTATION));

					if (Utils.fileExists(path)) {
						PicItem item = new PicItem(id, path, null);
						picItems.add(item);
						n++;
					}
					
					//保护：限制装载最大个数，防止内存OOM
					if (n>= maxCount)
						break;
					
				} while (cursor.moveToNext());
			}
			cursor.close();
		}
	}

	// ------------------------------------------------
	// maxxiang: 此函数可以废了，不再使用，统一自截剪
	private String queryMediaThumbPath(String id) {
		Cursor cursor = mResolver.query(URI_THUMBNAILS,
				new String[] { Thumbnails.DATA }, Thumbnails.IMAGE_ID + "=\""
						+ id + "\"", null, null);
		String strThumb = null;
		if (cursor == null) {
			return strThumb;
		}

		if (cursor.moveToFirst()) {
			strThumb = cursor.getString(0);
		}
		cursor.close();

		return strThumb;
	}

	// ------------------------------------------------

	private String getOrderBy() {
		return BaseColumns._ID + " desc";
	}
}
